<?
header('pragma: no-cache');
set_time_limit(0);
error_reporting (4096);
function AddChilds ($iClassId, $iMergingClassId, $iMerging, $tree) {
        $sQuery = "SELECT * FROM class WHERE parent_id = ".intval($iClassId);
        $i_num = getMultData($sQuery, $aClass);

        for ($i = 0; $i < $i_num; $i++) {
                $sQuery = "INSERT INTO merging_data SET merging_id = '".intval($iMerging)."', class_id = '".$aClass[$i]['id']."', parent_id = ".$iMergingClassId.", tree = '".$tree."'";
                insertRecord($sQuery);
                AddChilds($aClass[$i]['id'], mysql_insert_id(), $iMerging, $tree);
        }
}

function DeleteTree ($iClassId, $iMergingId) {
        $sQuery = "SELECT * FROM merging_data WHERE merging_id = ".intval($iMergingId)." AND parent_id = ".intval($iClassId);
        getMultData ($sQuery, $aClass);
        for ($i = 0, $size = sizeof($aClass); $i < $size; $i++) {
                DeleteTree($aClass[$i]['id'], $iMergingId);
        }
        $sQuery = "DELETE FROM merging_data WHERE merging_id = ".intval($iMergingId)." AND id = ".intval($iClassId);
        insertRecord ($sQuery);
}

function arOfIdtoString ($ar) {
	return implode(
    	",",
    	array_map(
        	create_function(
        		'$el',
        		'return $el["id"];'
        	),
        	$ar
    	)
	);
}

function show_page() {
  global $_GET, $data, $path, $style, $session_id, $language, $term_Thing_ID, $header;
  if (isset($data["type"]) && $data["type"] == 2) { //does the user have admin rights?
    if (!isset($_GET["act"])) $_GET["act"] = "page";
    switch ($_GET["act"]) {
            case 'addclass':
                    $iClassId = intval($_REQUEST['cid']);
                    $iParentId = substr($_REQUEST['parent_id'], 1);
                    $iMergingId = intval($_REQUEST['mid']);
                    
                    $sQuery = "SELECT COUNT(*) as quan FROM merging_data WHERE merging_id = '".$iMergingId."' AND class_id = '".$iClassId."'";
                    getData ($sQuery, $res);

                    $error_msg = '';
                    if ($res['quan'] == 0) {
                            $tree = trim($_REQUEST['view'] ? $_REQUEST['view'] : 'domain');
                            $sQuery = "INSERT INTO merging_data SET merging_id = '".$iMergingId."', class_id = '".$iClassId."', parent_id = ".$iParentId.", link_type='".trim($_REQUEST['link_type'])."', tree = '".$tree."'";
                            insertRecord($sQuery);
                            AddChilds($iClassId, mysql_insert_id(), $iMergingId, $tree);
                    } else {
                    	$error_msg = getMessage('Error! This class exist in merging result!');
                    }

                    ob_get_clean();
                    header('Location: index.php?trg=merger&sid='.$session_id.'&act=subclasses_onto&mid='.$iMergingId.'&parent_class_id='.$_REQUEST['parent_id'].'&error='.urlencode($error_msg)."&view=".trim($_REQUEST['view']));
                    exit;
                break;

                case 'removeclass':
                    $classMergingId = intval(substr($_REQUEST['cid'], 1));
                    
                    $query = "SELECT class_id as id FROM merging_data WHERE id = ".$classMergingId;
                    getData($query, $class);
                    
                    $mid = intval($_REQUEST['mid']);
            		DeleteTree($classMergingId, $mid);
            		
            		$strListId = array();
                    
                    $query = "SELECT
                    	md.class_id as id
                    FROM acon
                    INNER JOIN merging_data as md ON (md.class_id IN (acon.class1_id, acon.class2_id))
                    WHERE md.merging_id = {$mid} AND {$class['id']} IN (acon.class1_id, acon.class2_id)";
                    getMultData($query, $classList);
                    if (sizeof ($classList)) $strListId[] = arOfIdtoString($classList);
                    
                    $query = "SELECT
                    	md.class_id as id
                    FROM compatible as acon
                    INNER JOIN merging_data as md ON (md.class_id IN (acon.class1_id, acon.class2_id))
                    WHERE md.merging_id = {$mid} AND {$class['id']} IN (acon.class1_id, acon.class2_id)";
                    getMultData($query, $classList);
                    if (sizeof ($classList)) $strListId[] = arOfIdtoString($classList);
                    
                    $query = "SELECT
                    	md.class_id as id
                    FROM hierarchy as acon
                    INNER JOIN merging_data as md ON (md.class_id IN (acon.parent_class_id, acon.child_class_id))
                    WHERE md.merging_id = {$mid} AND {$class['id']} IN (acon.parent_class_id, acon.child_class_id)";
                    getMultData($query, $classList);
                    if (sizeof ($classList)) $strListId[] = arOfIdtoString($classList);
                    
                    $sResult = '';
                    foreach ($strListId as $id) {
                    	$sResult .= '<id><text><![CDATA['.
		            	__get_all_properties_for_new_onto (
		            		intval($id),
		            		intval($_REQUEST['mid'])
		        		).']]></text><div_id>prop_'.md5($id).'</div_id></id>';
                    }
                    
                    $contents = '<?xml version="1.0" encoding="utf-8" ?><result>'.$sResult.'</result>';
                    header ("Content-Type: text/xml");
                break;
                
                case 'viewclasses':
                    $contents = EchoNewOnto(intval($_REQUEST['mid']));

                    header ("Content-Type: text/xml");
                break;

      default: //including "page"
        if (!$_REQUEST['merging_id']) {
                $sQuery = "SELECT * FROM session WHERE session_id = '".mysql_escape_string($_GET['sid'])."'";
                getData($sQuery, $aSession);

                switch (intval($_REQUEST['typeo'])) {
                        case 1:
                                $iResult = $iFirst = $iSecond = 1;
                        break;
                        case 4:
                        case 2:
                                $iResult = 0;
                                $iFirst = 1;
                                $iSecond = 2;
                        break;
                        case 3:
                                $iResult = $iFirst = $iSecond = 2;
                        break;
                        case 5:
                                $iResult = $iFirst = 0;
                                $iSecond = 1;
                            break;
                            case 6:
                                $iResult = $iFirst = 0;
                                $iSecond = 2;
                            break;
                }

                $name = trim($_REQUEST['name']);
                if ($name && !in_array(intval($_REQUEST['typeo']), array(5, 6))) {
                        $sQuery = "SELECT COUNT(*) as quan FROM term t, ontology o WHERE o.term_id = t.id AND t.text LIKE '".mysql_escape_string($name)."'";
                        getData ($sQuery, $cnt1);

                        $sQuery = "SELECT COUNT(*) as quan FROM merging WHERE name LIKE '".mysql_escape_string($name)."' OR tmo_name LIKE '".mysql_escape_string($name)."' OR domain_name LIKE '".mysql_escape_string($name)."'";
                        getData ($sQuery, $cnt2);

                        if ($cnt1['quan'] > 0) {
                            header('Location: index.php?trg=merger_choise&sid='.$_REQUEST['sid'].'&name='.urlencode($name).'&error='.urlencode(getMessage('Name exist!')));
                            exit;
                        } else if ($cnt2['quan'] > 0) {
                        	$sQuery = "SELECT
                        		CONCAT(fname, ' ', lname) as name
                        	FROM merging
                        	INNER JOIN user ON (merging.user_id = user.user_id)
                        	WHERE
                        		merging.name LIKE '".mysql_escape_string($name)."' OR
                        		merging.tmo_name LIKE '".mysql_escape_string($name)."' OR
                        		merging.domain_name LIKE '".mysql_escape_string($name)."'";
	                        getData ($sQuery, $cnt2);
                        	header('Location: index.php?trg=merger_choise&sid='.$_REQUEST['sid'].'&name='.urlencode($name).'&error='.urlencode (sprintf(getMessage('Name exist and develop!'), $cnt2['name'])));
                            exit;
                        }
                }

                $sQuery = "INSERT INTO merging SET name = '".mysql_escape_string(trim($_REQUEST['name']))."', user_id = '".intval($aSession['user_id'])."', result = ".$iResult.", first = ".$iFirst.", second = ".$iSecond.", type = ".intval ($_REQUEST['typeo']);
                insertRecord($sQuery);

                $iMergingId = mysql_insert_id();

                if (in_array(intval($_REQUEST['typeo']), array(5,6))) {
                        $sQuery = "UPDATE merging SET merging_type = 'external' WHERE id = ".$iMergingId;
                        insertRecord($sQuery);
                }
        } else {
                $iMergingId = intval($_REQUEST['merging_id']);
        }

        global $error_name, $domain_name, $tmo_name;
        $error_name = '';
        if ($_REQUEST['act'] == 'save_names') {
                $domain_name = trim($_REQUEST['domain_name']);
                $tmo_name = trim($_REQUEST['tmo_name']);

                if ($domain_name) {
                        $sQuery = "SELECT COUNT(*) as quan FROM term t, ontology o WHERE o.term_id = t.id AND t.text LIKE '".mysql_escape_string($domain_name)."'";
                        getData ($sQuery, $cnt1);

                        $sQuery = "SELECT COUNT(*) as quan FROM merging WHERE name LIKE '".mysql_escape_string($domain_name)."' OR tmo_name LIKE '".mysql_escape_string($domain_name)."' OR domain_name LIKE '".mysql_escape_string($domain_name)."'";
                        getData ($sQuery, $cnt2);

                        if ($cnt1['quan'] + $cnt2['quan'] > 0) {
                                $error_name = getMessage('Name exist!');
                        } else {
                                $sQuery = "UPDATE merging SET domain_name = '".mysql_escape_string($domain_name)."' WHERE id = ".$iMergingId;
                                insertRecord($sQuery);
                                $domain_name = '';
                        }
                }

                if ($tmo_name) {
                        $sQuery = "SELECT COUNT(*) as quan FROM term t, ontology o WHERE o.term_id = t.id AND t.text LIKE '".mysql_escape_string($tmo_name)."'";
                        getData ($sQuery, $cnt1);

                        $sQuery = "SELECT COUNT(*) as quan FROM merging WHERE name LIKE '".mysql_escape_string($tmo_name)."' OR tmo_name LIKE '".mysql_escape_string($tmo_name)."' OR domain_name LIKE '".mysql_escape_string($tmo_name)."'";
                        getData ($sQuery, $cnt2);

                        if ($cnt1['quan'] + $cnt2['quan'] > 0) {
                                $error_name = getMessage('Name exist!');
                        } else {
                                $sQuery = "UPDATE merging SET tmo_name = '".mysql_escape_string($tmo_name)."' WHERE id = ".$iMergingId;
                                insertRecord($sQuery);
                                $tmo_name = '';
                        }
                }
        }

        if ($_REQUEST['act'] == 'setao') {
			$sQuery = "UPDATE merging SET external_onto_id = ".intval($_REQUEST['ao'])." WHERE id = ".$iMergingId;
			insertRecord($sQuery);
			$sQuery = "DELETE FROM merging_data WHERE merging_id = ".$iMergingId;
			insertRecord($sQuery);
        }

        $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
        getData($sQuery, $aMerging);
        
        $iAOandAO = intval ($aMerging['type'] == 4);
        $iDomainAndTMO = intval ($aMerging['type'] == 2);
        
        $error_msg = '';
        if ($iAOandAO || $iDomainAndTMO) {
            if (!$aMerging['tmo_name'] || !$aMerging['domain_name']) {
                $error_msg = 'alert (\''.getMessage('Input name of ontologies!').'\'); return false;';
            }
        }


        $ONSAVE = '';
        if ($iDomainAndTMO || $iAOandAO) {
                if (!$aMerging['domain_name'] || !$aMerging['tmo_name']) {
                        $ONSAVE = "alert ('".getMessage('Input name for doman and task and method ontology!')."'); return false;";
                }
        }

        $sTemplateName = "merger.htm";
        $filename = $path[$style]["tpl"]."/".$sTemplateName;
        $fp = fopen($filename, "r");
        $contents = fread($fp, filesize ($filename));
        fclose ($fp);

        $contents = str_replace("%DTMO%", print_r(intval($iDomainAndTMO), true), $contents);
        $contents = str_replace("%AO2%", print_r(intval($iAOandAO), true), $contents);

        $contents = str_replace("%ROOT_CSS%", $path[$style]["css"], $contents);
        $contents = str_replace("%ROOT_IMG%", $path[$style]["img"], $contents);
        $contents = str_replace("%ROOT_JAVA%", $path[$style]["java"], $contents);

        $contents = str_replace("%SID%", $session_id, $contents);
        $contents = str_replace("%TRG%", "merger", $contents);
        $contents = str_replace("%SEARCH%", getMessage("Search"), $contents);
        $contents = str_replace("%TYPEO%", $_GET["typeo"], $contents);
        $contents = str_replace("%ONSAVE%", $ONSAVE, $contents);

        $contents = str_replace("%LOGOUT%", getMessage("Logout"), $contents);
        $contents = str_replace("%MAINMENU%", getMessage("Main menu"), $contents);
        $contents = str_replace("%MERG%", getMessage("Ontology merger"), $contents);

        $contents = str_replace('%Are you sure?%', getMessage('Are you sure?'), $contents);
        $contents = str_replace('%Save!%', getMessage('Save!'), $contents);
        $contents = str_replace('%Add%', getMessage('Add'), $contents);
        $contents = str_replace('%Delete%', getMessage('Delete'), $contents);

        $contents = str_replace('%TMO_NAME%', $tmo_name, $contents);
        $contents = str_replace('%DOMAIN_NAME%', $domain_name, $contents);
        $contents = str_replace('%ERROR_NAME%', $error_name, $contents);

        $contents = str_replace('%Error! Empty result!%', getMessage('Error! Empty result!'), $contents);
        $contents = str_replace('%Back to merger%', getMessage('Back to merger'), $contents);

        $contents = str_replace('%ERROR_MSG%', $error_msg, $contents);

        $contents = str_replace("%MID%", $iMergingId, $contents);

        $contents = str_replace("%SETAO%", intval($aMerging['external_onto_id'] > 0), $contents);

        $externalOnto = '';
        if ($aMerging['merging_type'] == 'external' && $aMerging['external_onto_id'] > 0) {
            $sQuery = "select t.text as `name` from ontology o, term t where o.id = ".intval($aMerging['external_onto_id'])." and".
                      " o.term_id = t.id and".
                      " t.lang_id = ".$language["content"];
            getData ($sQuery, $externalOnto);
            $externalOnto = $externalOnto['name'];
        }

        $askReplace = sprintf(getMessage('askReplace'), $externalOnto);

        $contents = str_replace("%ASKREPLACE%", $askReplace, $contents);
        $contents = str_replace("%EXTERNALMERGE%", intval($aMerging['merging_type'] == 'external'), $contents);

        $contents = str_replace("%Select base ontology!%", getMessage('Select base ontology!'), $contents);

        if ($iAOandAO) {
        	$sQuery = "select t.text, o.id from ontology o, term t where o.type_id = 0 and".
                          " o.term_id = t.id and".
                          " t.lang_id = ".$language["content"].
                          " order by t.text;";
        } else {
        	$sQuery = "select t.text, o.id from ontology o, term t where o.type_id = ".$aMerging['first']." and".
                          " o.term_id = t.id and".
                          " t.lang_id = ".$language["content"].
                          " order by t.text;";
        }
        $contents = str_replace("%ONTOTREELEFT%", ShowOntoTree($sQuery, $aMerging['merging_type'] == 'external', 'left'), $contents);


        ////////////////////////////////////

        if ($iAOandAO) {
        	$sQuery = "select t.text, o.id from ontology o, term t where o.type_id = 0 and".
                          " o.term_id = t.id and".
                          " t.lang_id = ".$language["content"].
                          " order by t.text;";
        } else {
        	$sQuery = "select t.text, o.id from ontology o, term t where o.type_id = ".$aMerging['second']." and".
                          " o.term_id = t.id and".
                          " t.lang_id = ".$language["content"].
                          " order by t.text;";
        }

        $contents = str_replace("%ONTOTREERIGHT%", ShowOntoTree($sQuery, false, 'right'), $contents);

        header ($header["html"]);
      break;

      case "save":
		require('MERGER/class.copy.php');
		$iOntoId = SaveMergingResult (intval($_REQUEST['mid']));
		
		ob_get_clean();
		header("Location: index.php?trg=merger_choise&sid=".$session_id."&result_message=".urlencode(getMessage('Create ontology').' '.$iOntoId));
      break;


	case 'subclasses':
		ob_start();
		
		$mid = $_REQUEST['mid'];
		$sQuery = "SELECT * FROM merging WHERE id = ".$mid;
		getData($sQuery, $merging);
		$base_onto_id = -1;
		if ($merging['type'] == 4) {
			$sQuery = "
			select
				c.base_onto_id as onto_id,
				o.type_id
			from class as c
			inner join ontology as o ON(o.id = c.base_onto_id)
			where
				c.onto_id = (select onto_id from class where id = ".intval($_REQUEST['parent_class_id']).") and
				c.base_onto_id > 0 and
				o.type_id = ".($_REQUEST['align'] == 'left' ? 1 : 2)."
			group by c.base_onto_id";
			getData($sQuery, $onto);
			$base_onto_id = $onto['onto_id'];
		}
		
		EchoChildClasses(intval($_REQUEST['parent_class_id']), 1, $base_onto_id, $_REQUEST['align']);
		$sResult = ob_get_clean();
		if (!$sResult) {
			global $language;
			$query = "
			SELECT
				t.`text`
			FROM class as c
			INNER JOIN ontology as o ON (o.id = c.onto_id)
			INNER JOIN term as t ON (t.id = o.term_id)
			WHERE
				c.id = ".intval($_REQUEST['parent_class_id'])." AND
				t.lang_id = ".intval($language['content']);
			getData($query, $onto);
			$sResult = sprintf(getMessage("Ontology is empty!"), $onto['text']);
			$contents = '<?xml version="1.0" encoding="utf-8" ?><alert><![CDATA['.$sResult.']]></alert>';
		} else {
			$contents = '<?xml version="1.0" encoding="utf-8" ?><result><![CDATA['.$sResult.']]></result>';
		}
		
		header ("Content-Type: text/xml");
		
	break;
	
	case 'subclasses_onto':
		$iMergingId = intval($_REQUEST['mid']);
		$sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
		getData ($sQuery, $aMerging);
		ob_start();
		if ($aMerging['merging_type'] == 'external') {
            _EchoNewOnto_external($iMergingId, substr($_REQUEST['parent_class_id'], 1), 1, (substr($_REQUEST['parent_class_id'], 0, 1) == 'c' ? 'class' : 'merging_data'));
        } else {
        	_EchoNewOnto($iMergingId, substr($_REQUEST['parent_class_id'], 1));
        }
		$sResult = ob_get_clean();
		
		$error = htmlspecialchars(trim($_REQUEST['error']));
		
		header ("Content-Type: text/xml");
		$contents = '<?xml version="1.0" encoding="utf-8" ?><result><text><![CDATA['.$sResult.']]></text>';
		if ($error) {
			$contents .= "<error>{$error}</error>";
		}
		$contents .= "</result>";
	break;
    }
            header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
            header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
            header ("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1
            header ("Pragma: no-cache");                          // HTTP/1.0
            print ($contents);
  }
  else { //no admin rights
    header("Location: index.php?trg=main&sid=".$session_id);
  }
}

function __get_child ($iClassId, $forMerging, $iMergingId) {
	static $proxy = null;
	if (!$proxy) {
		$proxy = array();
	}
	if ($proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)]) {
		return $proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)];
	}
	
	$return = array();
	
	for (;;) {
		$sQuery = "SELECT id FROM class WHERE parent_id = ".$iClassId;
	    getData ($sQuery, $class);
	    $iClassId = $class['id'];
	    if ($iClassId == 0) {
	            break;
	    }
	    $aRet[] = $iClassId;
    }

	if ($forMerging) {
		$query = "SELECT id FROM merging_data WHERE class_id = ".$aRet[0]." AND merging_id = ".$iMergingId;
		getData ($sQuery, $class);
    	$iClassId = $class['id'];
    	for (;$iClassId;) {
    		$query = "SELECT id, class_id FROM merging_data WHERE parent_id = ".$iClassId;
    		getData($query, $class);
    		$iClassId = $class['id'];
    		$aRet[] = intval($class['class_id']);
    		if ($iClassId == 0) {
    			break;
    		}
    	}
	}
	
	$proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)] = $return;
	
	return $return;
}

function __get_parent ($iClassId, $forMerging, $iMergingId, $onlyMerging = 0) {
	static $proxy = null;
	if (!$proxy) {
		$proxy = array();
	}
	if ($proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)]) {
		return $proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)];
	}
	
    $aRet = array();
    $aRet[] = $iClassId;
    for (;!$onlyMerging;) {
        $sQuery = "SELECT parent_id as id FROM class WHERE id = ".$iClassId;
        getData ($sQuery, $class);
        $iClassId = $class['id'];
        if ($iClassId == 0 || $class['parent_id'] == 0) {
                break;
        }
        if (!in_array($iClassId, $aRet)) {$aRet[] = $iClassId;}
    }
    if ($forMerging) {
    	$sQuery = "SELECT id FROM merging_data WHERE class_id = ".$aRet[0]." AND merging_id = ".$iMergingId;
    	getData ($sQuery, $class);
    	$iClassId = $class['id'];
    	for (;;) {
            $sQuery = "SELECT parent_id as id, class_id FROM merging_data WHERE id = ".$iClassId;
            getData ($sQuery, $class);
            $iClassId = $class['id'];
            if (!in_array($class['class_id'], $aRet)) {$aRet[] = $class['class_id'];}
            if ($iClassId == 0) {
                    break;
            }
        }	
    }
    $proxy[intval($iClassId)][intval($forMerging)][intval($iMergingId)][intval($onlyMerging)] = $aRet;
    return $aRet;
}

function __existClassInMerging ($classId, $mergingId) {
	$query = "SELECT COUNT(*) as quan FROM merging_data WHERE merging_id = ".intval($mergingId)." AND class_id = ".intval($classId);
	getData($query, $res);
	return ($res['quan'] == 1);
}

function getClassName ($classId) {
	global $langugage;
	$query = "
	SELECT
		t.`text`
	FROM class as c
	INNER JOIN term as t ON (t.id = c.term_id)
	WHERE c.id = ".intval($classId)." AND term_id != 36 AND lang_id = ".intval($language['content']);
	getData($query, $term);
	return $term['text'];
}

function __get_acon ($classId, $forMerging, $iMergingId) {
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
    global $language;
    
    $ownPair = array();
    $inheritPair = array();
    foreach ($aClassId as $id) {
    	$pair = array();
    	$pair['1'] = $id;
		$query = "SELECT 
        	class1_id,
        	class2_id
        FROM acon
        WHERE {$id} IN (class1_id, class2_id)";
    	getMultData($query, $p);
    	foreach ($p as $_p) {
        	if ($_p['class1_id'] == $id) {
        		$pair['2'] = $_p['class2_id'];
        	} else {
        		$pair['2'] = $_p['class1_id'];
        	}
        	
        	if ($pair['2'] != $aClassId[0]) {
        		if ($id != $aClassId[0]) {
	        		$inheritPair[] = $pair;
	        	} else {
	        		$ownPair[] = $pair;
	        	}
        	}
    	}
    }
    
    if ($forMerging) {
    	for ($i = 0, $size = sizeof($ownPair); $i < $size; $i++) {
    		if (!__existClassInMerging($ownPair[$i]['1'], $iMergingId) || !__existClassInMerging($ownPair[$i]['2'], $iMergingId)) {
    			unset($ownPair[$i]);
    		}
    	}
    	for ($i = 0, $size = sizeof($inheritPair); $i < $size; $i++) {
    		if (/*!__existClassInMerging($inheritPair[$i]['1'], $iMergingId) || */!__existClassInMerging($inheritPair[$i]['2'], $iMergingId)) {
    			unset($inheritPair[$i]);
    		}
    	}
    }
    
    $result = array();
    foreach ($ownPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => '', 'text' => getClassName($pair['2']));
    }
    foreach ($inheritPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => 'inh', 'text' => getClassName($pair['2']));
    }
    return $result;
}

function __get_compatible ($classId, $forMerging, $iMergingId) {
	global $language;
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
    
    $ownPair = array();
    $inheritPair = array();
    foreach ($aClassId as $id) {
    	$pair = array();
    	$pair['1'] = $id;
    	$query = "SELECT 
        	class1_id,
        	class2_id
        FROM compatible
        WHERE {$id} IN (class1_id, class2_id)";
    	getMultData($query, $p);
    	foreach ($p as $_p) {
        	if ($_p['class1_id'] == $id) {
        		$pair['2'] = $_p['class2_id'];
        	} else {
        		$pair['2'] = $_p['class1_id'];
        	}
        	
        	if ($pair['2'] != $aClassId[0]) {
        		if ($id != $aClassId[0]) {
	        		$inheritPair[] = $pair;
	        	} else {
	        		$ownPair[] = $pair;
	        	}
        	}
    	}
    }
    
    if ($forMerging) {
    	for ($i = 0, $size = sizeof($ownPair); $i < $size; $i++) {
    		if (!__existClassInMerging($ownPair[$i]['1'], $iMergingId) || !__existClassInMerging($ownPair[$i]['2'], $iMergingId)) {
    			unset($ownPair[$i]);
    		}
    	}
    	for ($i = 0, $size = sizeof($inheritPair); $i < $size; $i++) {
    		if (/*!__existClassInMerging($inheritPair[$i]['1'], $iMergingId) || */!__existClassInMerging($inheritPair[$i]['2'], $iMergingId)) {
    			unset($inheritPair[$i]);
    		}
    	}
    }
    
    $result = array();
    foreach ($ownPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => '', 'text' => getClassName($pair['2']));
    }
    foreach ($inheritPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => 'inh', 'text' => getClassName($pair['2']));
    }
    return $result;
}

function __get_hierarchy_child ($classId, $forMerging, $iMergingId) {
	global $language;
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
    
    $ownPair = array();
    $inheritPair = array();
    foreach ($aClassId as $id) {
    	$pair = array();
    	$pair['1'] = $id;
    	$query = "SELECT 
        	parent_class_id,
        	child_class_id
        FROM hierarchy
        WHERE {$id} = child_class_id";
    	getMultData($query, $p);
    	foreach ($p as $_p) {
    		$pair['2'] = $_p['parent_class_id'];
        	
        	if ($pair['2'] != $aClassId[0]) {
        		if ($id != $aClassId[0]) {
	        		$inheritPair[] = $pair;
	        	} else {
	        		$ownPair[] = $pair;
	        	}
        	}
    	}
    }
    
    if ($forMerging) {
    	for ($i = 0, $size = sizeof($ownPair); $i < $size; $i++) {
    		if (!__existClassInMerging($ownPair[$i]['1'], $iMergingId) || !__existClassInMerging($ownPair[$i]['2'], $iMergingId)) {
    			unset($ownPair[$i]);
    		}
    	}
    	for ($i = 0, $size = sizeof($inheritPair); $i < $size; $i++) {
    		if (/*!__existClassInMerging($inheritPair[$i]['1'], $iMergingId) || */!__existClassInMerging($inheritPair[$i]['2'], $iMergingId)) {
    			unset($inheritPair[$i]);
    		}
    	}
    }
    
    $result = array();
    foreach ($ownPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => '', 'text' => getClassName($pair['2']));
    }
    foreach ($inheritPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => 'inh', 'text' => getClassName($pair['2']));
    }
    return $result;	
}

function __get_hierarchy_parent ($classId, $forMerging, $iMergingId) {
	global $language;
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
	
	$result = array();
	$ownPair = array();
	$inheritPair = array();
	$query = "SELECT parent_class_id, child_class_id FROM hierarchy WHERE parent_class_id = ".intval($aClassId[0]);
	getMultData($query, $rel);
	foreach ($rel as $r) {
		$pair = array('1' => $r['parent_class_id']);
		if (!$forMerging) {
			$pair['2'] = $r['child_class_id'];
			$ownPair[] = $pair;
		} else {
			if (__existClassInMerging($r['child_class_id'], $iMergingId)) {
				$pair['2'] = $r['child_class_id'];
				$ownPair[] = $pair;
			} else {
				$child = __get_child($r['child_class_id'], $forMerging, $iMergingId);
				foreach ($child as $id) {
					if (__existClassInMerging($id, $iMergingId)) {
						$pair['2'] = $id;
						$inheritPair[] = $pair;
						break;
					}
				}
			}
		}
	}
    
    $result = array();
    foreach ($ownPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => '', 'text' => getClassName($pair['2']));
    }
    foreach ($inheritPair as $pair) {
    	$result[] = array('id' => $pair['2'], 'inherit' => 'inh', 'text' => getClassName($pair['2']));
    }
    return $result;	
}

function __get_attr ($classId, $type, $forMerging, $iMergingId) {
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
    global $language;
    $sQuery = "SELECT
    		term.id,
            term.text,
            IF(".($forMerging ? "NOT ISNULL(merging_data.class_id) AND (ISNULL(merging_data.class_id) OR class_attr.class_id != ".$aClassId[0].")" : "class_attr.class_id != ".$aClassId[0]).", 'inh', '') as inherit
    FROM class_attr
    INNER JOIN attr
    INNER JOIN term ";
    if ($forMerging) {
    	$sQuery .= " left join merging_data on (merging_data.merging_id=".$iMergingId." and merging_data.class_id = class_attr.class_id) ";
    }
    $sQuery .= " WHERE
            class_attr.attr_id = attr.id AND
            attr.term_id = term.id AND
            attr.type = ".intval($type)." AND
            class_attr.class_id IN (".implode(",", $aClassId).")";
    getMultData ($sQuery, $data);
    return $data;
}

function __get_synonyms ($classId, $forMerging, $iMergingId) {
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
    $sQuery = "
    SELECT
    		synonyms.id,
            synonyms.text,
            IF(class.id != ".$aClassId[0].", 'inh', '') as inherit
    FROM synonyms
    INNER JOIN class 
    WHERE
            synonyms.term_id = class.term_id AND
            class.id IN (".implode(",", $aClassId).")";
    getMultData ($sQuery, $aRet1);
    return $aRet1;
}

function getFunctionalRelationName ($relId) {
	global $langugage;
	$query = "
	SELECT
		t.`text`
	FROM func_constr as c
	INNER JOIN term as t ON (t.id = c.term_id)
	WHERE c.id = ".intval($relId)." AND term_id != 36 AND lang_id = ".intval($language['content']);
	getData($query, $term);
	return $term['text'];
}

function __get_func_constr ($classId, $forMerging, $iMergingId) {
	$aClassId = __get_parent($classId, $forMerging, $iMergingId);
	
	$query = "SELECT * FROM func_constr WHERE relation_type = 0 AND func_value IN (".implode(",", $aClassId).")";
	getMultData($query, $list);
	
	$ownPair = array();
	$inhPair = array();
	foreach ($list as $v) {
		if ($forMerging) {
			if (!__existClassInMerging($v['func_value'], $iMergingId) || !__existClassInMerging($v['relation_id'], $iMergingId)) {
				continue;
			}
		}
		
		if ($v['func_value'] == $classId) {
			$ownPair[] = array('id' => $v['id'], 'class' => $v['relation_id']);
		} else {
			$inhPair[] = array('id' => $v['id'], 'class' => $v['relation_id']);
		}
	}
	
	$query = "SELECT * FROM func_constr WHERE relation_type = 0 AND relation_id IN (".implode(",", $aClassId).")";
	getMultData($query, $list2);
	
	foreach ($list2 as $v) {
		if ($forMerging) {
			if (!__existClassInMerging($v['func_value'], $iMergingId) || !__existClassInMerging($v['relation_id'], $iMergingId)) {
				continue;
			}
		}
		
		if ($v['relation_id'] == $classId) {
			$ownPair[] = array('id' => $v['id'], 'class' => $v['func_value']);
		} else {
			$inhPair[] = array('id' => $v['id'], 'class' => $v['func_value']);
		}
	}

	$return = array();
	foreach ($ownPair as $p) {
		$return[] = array('id' => $p['id'], 'text' => getFunctionalRelationName($p['id']), 'inherit' => '');
	}
	
	foreach ($inhPair as $p) {
		$return[] = array('id' => $p['id'], 'text' => getFunctionalRelationName($p['id']), 'inherit' => 'inh');
	}
	
	return $return;
}

function __show_properties ($sName, $aValues) {
        global $path, $style;
        if (sizeof($aValues)) {
            list ($sRand, $sRand2) = explode(" ", microtime());
        	$sId = "acon_".md5($sRand);
            echo "<span><img
                    src='http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif'
                    border=0
                    onclick='
                    if (this.src == \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif\") {
                            this.src = \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/minus.gif\";
                            document.getElementById (\"".$sId."\").style.display = \"block\";
                    } else {
                            this.src = \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif\";
                            document.getElementById (\"".$sId."\").style.display = \"none\";
                    }'>";
            echo "<img src='".$path[$style]["img"]."/folder.png'>".$sName."</span>
            <div id=".$sId." style='display: none;'>
            ";
            for ($i = 0, $size = sizeof($aValues); $i < $size; $i++) {
                    echo "<img src='".$path[$style]["img"]."/Empty.gif'>";
                    echo "<img src='".$path[$style]["img"]."/Empty.gif'>";
                    echo "&nbsp;<img src=http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/".$aValues[$i]['inherit']."attr.png>&nbsp;";
                    echo $aValues[$i]['text']."<br/>";
            }
            echo "</div><br>";
        }
}

function __get_all_properties__ ($iClassId, $forMerging, $iMergingId = 0) {
		$aId = __get_parent($iClassId, $forMerging, $iMergingId);
        
        ob_start();
        __show_properties(getMessage('Attributes'), __get_attr($iClassId, 0, $forMerging, $iMergingId));
        __show_properties(getMessage('Input Attributes'), __get_attr($iClassId, 1, $forMerging, $iMergingId));
        __show_properties(getMessage('Output Attributes'), __get_attr($iClassId, 2, $forMerging, $iMergingId));
        __show_properties(getMessage('Associative Constraints'), __get_acon($iClassId, $forMerging, $iMergingId));
        __show_properties(getMessage('Compatibility'), __get_compatible($iClassId, $forMerging, $iMergingId));
        __show_properties(getMessage('Hierarchy').' ('.getMessage('child').')', __get_hierarchy_child($iClassId, $forMerging, $iMergingId));
        __show_properties(getMessage('Hierarchy').' ('.getMessage('parent').')', __get_hierarchy_parent($iClassId, $forMerging, $iMergingId));
        __show_properties(getMessage('Synonyms'), __get_synonyms($iClassId, $forMerging, $iMergingId));
        __show_properties(getMessage('Functional constraints'), __get_func_constr($iClassId, $forMerging, $iMergingId));
        $properties =  ob_get_clean();
        if ($properties) {
                return "<div style='padding-left: 16px;'>".$properties."</div>";
        }
        return "";
}


function __get_all_properties ($iClassId) {
        return __get_all_properties__($iClassId, false);
}

function __get_all_properties_for_new_onto ($iClassId, $iMergingId) {
        return __get_all_properties__($iClassId, true, $iMergingId);
}

function EchoChildClasses ($iClassId, $level = 1, $base_onto_id = -1, $align = 'left') {
        global $path, $style, $language;
        
        $add_sql = "";
        
        $sQuery = "SELECT c.id, t.text FROM class c, term t WHERE t.id = c.term_id AND c.parent_id = ".intval($iClassId)." AND t.lang_id = ".$language['content'];// . $add_sql;
        if ($base_onto_id != -1) {
        	$sQuery .= " AND c.base_onto_id = ".$base_onto_id;
        }
        $i_num = getMultData($sQuery, $aClass);

        for ($i = 0; $i < $i_num; $i++) {
                $sQuery = "SELECT COUNT(*) as quan FROM class c, term t WHERE t.id = c.term_id AND c.parent_id = ".intval($aClass[$i]['id'])." AND t.lang_id = ".$language['content'];
                getData($sQuery, $aChild);
                $iChild = $aChild['quan'];

                list ($sRand, $sRand2) = explode(" ", microtime());
            	$sRand = md5($sRand);

                echo "\r\n<div id=c".$aClass[$i]['id'].$sRand." class=level".($level).">";
                if ($iChild) {
                        echo "<img src='http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif' border=0 onclick='if (this.src == \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif\") {this.src = \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/minus.gif\"} else {this.src = \"http://".$_SERVER["SERVER_NAME"].$path[$style]["img"]."/plus.gif\"} CollapseClasses(\"cc".$aClass[$i]['id'].$sRand."\", ".$aClass[$i]['id'].", \"{$align}\");'>";
                } else {
                        echo "<img src='".$path[$style]["img"]."/Empty.gif'>";
                }
                echo "<img src=".$path[$style]["img"]."/class.png border=0>
                <span style='cursor: pointer' onclick='SelectClass (".$aClass[$i]['id'].", \"ca".$aClass[$i]['id'].$sRand."\")' id=ca".$aClass[$i]['id'].$sRand.">".$aClass[$i]['text']."</span>\r\n";
                echo __get_all_properties($aClass[$i]['id']);
                echo "<div id=cc".$aClass[$i]['id'].$sRand." style='display: none;padding-left: 16px;'></div>";
                echo "</div>\r\n";
        }
}

function ShowOntoTree ($sQuery, $onlyTop = false, $align = 'left') {
	global $path, $style, $language;
    $sRet = '';
    $i_num = getMultData($sQuery, $aOnto);
    $res = mysql_query($sQuery);

    list ($sRand, $sRand2) = explode(" ", microtime());
    $sRand = md5($sRand);

    for ($i = 0; $i < $i_num; $i++) {
            $sQuery = "SELECT c.id FROM class c, ontology o, term as t WHERE o.id = c.onto_id AND c.parent_id = 0 AND o.id = ".$aOnto[$i]['id']." AND t.id = o.term_id AND lang_id = ".$language["content"];
            getData($sQuery, $aClass);


            $sRet .= "<div id=o".$aOnto[$i]['id'].$sRand." class=onto>\r\n";
            $sRet .= "<img src=".$path[$style]["img"]."/ontology.png border=0>";

            if (!$onlyTop) {
                    $sRet .= "<a href=# onclick='CollapseClasses(\"i".$aOnto[$i]['id'].$sRand."\", \"".$aClass['id']."\", \"".$align."\");'>".$aOnto[$i]['text']."</a>\r\n";
            } else {
                    $sRet .= "<a href=# onclick='SetAO({$aOnto[$i]['id']});'>".$aOnto[$i]['text']."</a>\r\n";
            }

            $sRet .= "<div id=i".$aOnto[$i]['id'].$sRand." style='display: none;padding-left: 16px;'>\r\n";
            $sRet .= "</div>\r\n";
            $sRet .= "</div>\r\n";
    }
    return $sRet;
}

function EchoNewOnto ($iMergingId) {
        global $path, $style, $language;
        $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
        getData($sQuery, $aMerging);

        $sQuery = "SELECT * FROM session WHERE session_id = '".mysql_escape_string($_GET['sid'])."'";
        getData($sQuery, $aSession);

        if ($aMerging['merging_type'] == 'external') {
                if (!$aMerging['external_onto_id']) {
                        $aMerging['name'] = getMessage('Select base ontology!');
                } else {
                        $sQuery = "SELECT `text` as name FROM ontology as o
                        INNER JOIN term as t ON (o.term_id = t.id)
                        WHERE lang_id = '".$language["content"]."' AND o.id = ".$aMerging['external_onto_id'];
                        getData ($sQuery, $aOntology);
                        $aMerging['name'] = $aOntology['name'];
                }
        }

        ob_start();

        $sQuery = "SELECT COUNT(*) as quan FROM merging_data WHERE merging_id = ".$iMergingId;
        getData ($sQuery, $aCount);
        $iCount = $aCount['quan'];

        echo '<?xml version="1.0" encoding="utf-8" ?>'."\r\n";
        echo '<Info InfoId="%INFO_ID%" Name="" NewID="%ID%" NewDatHref="%DatHref%" NewImg="%IMG%" Reload="%RELOAD%" var_quan="'.$iCount.'">'."\r\n";
        echo '  <InfoGroup GroupId="0" Title="'.htmlspecialchars($aMerging['name']).'">'."\r\n";

        ob_start();
        
        $iAOandAO = intval ($aMerging['type'] == 4);
        $iDomainAndTMO = intval ($aMerging['type'] == 2);
        
        //global $iDomainAndTMO, $iAOandAO;

/*        if ($aMerging['first'] == 1 && $aMerging['second'] == 2) {
            $iDomainAndTMO = 1;
    	} elseif ($aMerging['first'] == 0 && $aMerging['second'] == 0) {
            $iAOandAO = 1;
        } else {
            $iAOandAO = 0;
            $iDomainAndTMO = 0;
    	}*/

        if ($iDomainAndTMO || $iAOandAO) {
                $error_name = trim($_REQUEST['error_name']);
                $domain_name = trim($_REQUEST['domain_name']);
                $tmo_name = trim($_REQUEST['tmo_name']);
                echo "
                <form method=post action=\"index.php?trg=merger&sid=".$_REQUEST['sid']."&merging_id=".$aMerging['id']."\">
                <input type=hidden name=act value=save_names>
                {$error_name}
                <table border=0 width=99% cellpadding=0 cellspacing=1>
                        <tr>
                                <td>".getMessage('Domain ontology name')."</td>
                                <td><input type=text name=domain_name value='".htmlspecialchars($domain_name ? $domain_name : $aMerging['domain_name'])."' style='width: 100px;'>
                        </tr>
                        <tr>
                                <td>".getMessage('Task and Method ontology name')."</td>
                                <td><input type=text name=tmo_name value='".htmlspecialchars($tmo_name ? $tmo_name : $aMerging['tmo_name'])."' style='width: 100px;'>
                        </tr>
                        <tr>
                                <td>&nbsp;</td>
                                <td><input type=submit value='Save!'></td>
                        </tr>
                </table>
                </form>
                ";

                echo "<a href='javascript: DomainOnly();'>".getMessage('Domain Ontology')."</a>&nbsp;&nbsp;&nbsp;&nbsp;";
                echo "<a href='javascript: TMOOnly();'>".getMessage('TM Ontology')."</a>";
        }
        $sId = 'cfcd208495d565ef66e7dff9f98764da';

        if ($_REQUEST['oc'][0] == 1) {
                $img = 'plus';
                $div_style = 'display: none;';
        } else {
                $img = 'minus';
                $div_style = 'display: block;';
        }


        $iParentId = 0;
        if ($aMerging['merging_type'] == 'external') {
                $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
                getData($sQuery, $aMerging);
                $sQuery = "SELECT id FROM class WHERE parent_id = 0 AND onto_id = ".$aMerging['external_onto_id'];
                getData($sQuery, $aClass);
                $iParentId = $aClass['id'];
        }

        echo '<div class=level0 id=new'.$iParentId.'_main>
        <img src="http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/'.$img.'.gif" border=0 onclick="if (this.src == \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\') {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/minus.gif\'} else {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\'} if ($(\''.$sId.'\').style.display == \'none\') {$(\''.$sId.'\').style.display = \'block\'; aOpenClosed[0] = 0;} else {$(\''.$sId.'\').style.display = \'none\'; aOpenClosed[0] = 1;}">
        <img src='.$path[$style]["img"].'/class.png border=0>
        <span id=new'.$iParentId.' style="cursor:pointer;" onclick="SetParentId'.($aMerging['merging_type'] == 'external' ? '_external' : '').' (\''.($aMerging['merging_type'] == 'external' ? 'c' : 'm').intval($iParentId).'\', \''.$sId.'\', 1)">Thing</span>
        <div id="'.$sId.'" style="'.$div_style.'">';
        if ($aMerging['merging_type'] == 'external') {
                _EchoNewOnto_external ($iMergingId);
        } else {
                _EchoNewOnto ($iMergingId);
        }

        echo "</div></div>";
         $sClassList = ob_get_clean();

        echo '    <InfoNode Type="Label" NodeId="noc'.($aClass['id']).'" Title="" Value="'.htmlspecialchars($sClassList).'" Additional="%ADDITIONAL%"></InfoNode>'."\r\n";
        echo "  </InfoGroup>\r\n";
        echo "</Info>";

        return ob_get_clean();
}

function _EchoNewOnto_external ($iMergingId, $iParentId = 0, $level = 1, $table = 'class') {
		global $language;
        $iMergingId = intval($iMergingId);
        
        $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
        getData($sQuery, $aMerging);

        if ($table == 'class') {
                if (!$iParentId) {
                        $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
                        getData($sQuery, $aMerging);
                        if (!$aMerging['external_onto_id']) {
                                return '';
                        }
                        $sQuery = "SELECT id FROM class WHERE parent_id = 0 AND onto_id = ".$aMerging['external_onto_id'];
                        getData($sQuery, $aClass);
                        $iParentId = $aClass['id'];
                }
                $sQuery = "(SELECT c.id, c.id as class_id, c.parent_id, t.text as name, 'class' as `table` FROM class as c
INNER JOIN term as t ON (t.id = c.term_id)
WHERE c.parent_id = ".intval($iParentId)." AND t.lang_id = '".$language['content']."')
UNION
(SELECT md.id, md.class_id, md.parent_id, t.text as name, 'merging_data' as `table` FROM merging_data as md
INNER JOIN class as c ON (c.id = md.class_id)
INNER JOIN term as t ON (t.id = c.term_id)
WHERE link_type = 'external' AND md.parent_id = ".intval($iParentId)." AND t.lang_id = '".$language['content']."'
AND md.merging_id = '".$iMergingId."')";
        } elseif ($table == 'merging_data') {
                $sQuery = "
SELECT
        `md`.class_id as class_id,
        t.`text` as name,
        `md`.id as id,
        'merging_data' as `table`
FROM
        merging_data `md`,
        class c,
        term t,
        ontology o
WHERE
        `md`.merging_id = '".$iMergingId."' AND
        c.id = `md`.class_id AND
        c.term_id = t.id AND
        `md`.parent_id = '".intval($iParentId)."' AND
        o.id = c.onto_id AND t.lang_id = '".$language['content']."'";
        }

        //global $iDomainAndTMO, $iAOandAO;
        
        $iAOandAO = intval ($aMerging['type'] == 4);
        $iDomainAndTMO = intval ($aMerging['type'] == 2);
        
        if ($iDomainAndTMO || $iAOandAO) {
                $sQuery .= " AND o.type_id = ".($_GET['view'] == 'tmo' ? 2 : 1);
        }
        $i_num = getMultData($sQuery, $aClass);

        global $path, $style;

        for ($i = 0; $i < $i_num; $i++) {
                if ($aClass[$i]['table'] == 'class') {
                        $sQuery = "(SELECT COUNT(*) as quan FROM class as c
INNER JOIN term as t ON (t.id = c.term_id)
WHERE c.parent_id = ".intval($aClass[$i]['id'])." AND t.lang_id = '".$language['content']."')
UNION
(SELECT COUNT(*) as quan FROM merging_data as md
INNER JOIN class as c ON (c.id = md.class_id)
INNER JOIN term as t ON (t.id = c.term_id)
WHERE link_type = 'external' AND md.parent_id = ".intval($aClass[$i]['id'])."
AND md.merging_id = '".$iMergingId."' AND t.lang_id = '".$language['content']."')";
                } else {
                        $sQuery = "
                                SELECT
                                        COUNT(*) as quan
                                FROM
                                        merging_data `md`,
                                        class c,
                                        term t,
                                        ontology o
                                WHERE
                                        `md`.merging_id = '".$iMergingId."' AND
                                        c.id = `md`.class_id AND
                                        c.term_id = t.id AND
                                        `md`.parent_id = '".intval($aClass[$i]['id'])."' AND
                                        o.id = c.onto_id AND t.lang_id = '".$language['content']."'";
                }

                getMultData($sQuery, $aChild);
                $iChild = intval($aChild[0]['quan']) + intval($aChild[1]['quan']);

                if ($_REQUEST['oc'][$aClass[$i]['id']] == 1) {
                        $img = 'plus';
                        $div_style = 'display: none;';
                } else {
//                        $img = 'minus';
//                        $div_style = 'display: block;';
						$img = 'plus';
                        $div_style = 'display: none;';
                }

                $letter = substr($aClass[$i]['table'], 0, 1);
                $sId = md5($aClass[$i]['id']);
                echo '
                <div class="level0" id="'.$sId.'_main">
                '.($iChild ? '<img src="http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/'.$img.'.gif" border=0 onclick="if (this.src == \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\') {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/minus.gif\'; aOpenClosed['.$aClass[$i]['id'].'] = 0;} else {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\'} if ($(\''.$sId.'\').style.display == \'none\') {$(\''.$sId.'\').style.display = \'block\'; loadChildClasses (\''.$letter.$aClass[$i]['id'].'\', \''.$sId.'\', \''.$aClass[$i]['table'].'\');} else {$(\''.$sId.'\').style.display = \'none\'; aOpenClosed['.$aClass[$i]['id'].'] = 1;}">' : "<img src='".$path[$style]["img"]."/Empty.gif'>").'
                <img src='.$path[$style]["img"].'/class.png border=0>
                <span id="new'.md5($aClass[$i]['class_id']).'" style="cursor: pointer;" onclick="SetParentId_external(\''.$letter.$aClass[$i]['id'].'\', \''.$sId.'\', '.intval($aClass[$i]['table'] == 'class').');">'.$aClass[$i]['name'].'</span>';
                echo "\n<span id=prop_".md5($aClass[$i]['id']).">\n";
                if ($aClass[$i]['table'] != 'class') {
                        echo __get_all_properties_for_new_onto ($aClass[$i]['class_id'], $iMergingId);
                } else {
                        echo __get_all_properties ($aClass[$i]['class_id']);
                }
                echo "\n</span>\n";
                echo '<div id="'.$sId.'" style="'.$div_style.'">';
                //_EchoNewOnto_external($iMergingId, $aClass[$i]['id'], $level + 1, $aClass[$i]['table']);
                echo '</div></div>';
        }
}

function _EchoNewOnto ($iMergingId, $iParentId = 0, $level = 1) {
		global $language;
        $iMergingId = intval($iMergingId);
        
        $sQuery = "SELECT * FROM merging WHERE id = ".$iMergingId;
        getData($sQuery, $aMerging);

        $sQuery = "
SELECT
        `md`.class_id as id,
        t.`text`,
        `md`.id as mdid
FROM
        merging_data `md`,
        class c,
        term t,
        ontology o
WHERE
        `md`.merging_id = '".$iMergingId."' AND
        c.id = `md`.class_id AND
        c.term_id = t.id AND 
        `md`.parent_id = '".intval($iParentId)."' AND
        o.id = c.onto_id AND t.lang_id = '".$language['content']."'
";
        //global $iDomainAndTMO, $iAOandAO;
        
        $iAOandAO = intval ($aMerging['type'] == 4);
        $iDomainAndTMO = intval ($aMerging['type'] == 2);
        
        if ($iDomainAndTMO || $iAOandAO) {
                $sQuery .= " AND md.tree = '".($_REQUEST['view'] ? $_REQUEST['view'] : 'tmo')."'";
        }
        $i_num = getMultData($sQuery, $aClass);

        global $path, $style;

        for ($i = 0; $i < $i_num; $i++) {

$sQuery = "
SELECT
        COUNT(*) as quan
FROM
        merging_data `md`,
        class c,
        term t,
        ontology o
WHERE
        `md`.merging_id = '".$iMergingId."' AND
        c.id = `md`.class_id AND
        c.term_id = t.id AND
        `md`.parent_id = '".intval($aClass[$i]['mdid'])."' AND
        o.id = c.onto_id
";
                getData($sQuery, $aChild);
                $iChild = $aChild['quan'];

                if ($_REQUEST['oc'][$aClass[$i]['mdid']] == 1) {
                        $img = 'plus';
                        $div_style = 'display: none;';
                } else {
//                        $img = 'minus';
//                        $div_style = 'display: block;';
                        $img = 'plus';
                        $div_style = 'display: none;';
                }

                $sId = md5($aClass[$i]['mdid']);
                echo '
                <div class="level0" id="'.$sId.'_main">
                '.($iChild ? '<img src="http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/'.$img.'.gif" border=0 onclick="if (this.src == \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\') {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/minus.gif\'; aOpenClosed['.$aClass[$i]['mdid'].'] = 0;} else {this.src = \'http://'.$_SERVER["SERVER_NAME"].$path[$style]["img"].'/plus.gif\'} if ($(\''.$sId.'\').style.display == \'none\') {$(\''.$sId.'\').style.display = \'block\'; loadChildClasses (\'m'.$aClass[$i]['mdid'].'\', \''.$sId.'\');} else {$(\''.$sId.'\').style.display = \'none\'; aOpenClosed['.$aClass[$i]['mdid'].'] = 1;}">' : "<img src='".$path[$style]["img"]."/Empty.gif'>").'
                <img src='.$path[$style]["img"].'/class.png border=0>
                <span id="new'.$aClass[$i]['mdid'].'" style="cursor: pointer;" onclick="SetParentId(\'m'.$aClass[$i]['mdid'].'\', \''.$sId.'\');">'.$aClass[$i]['text'].'</span>
                ';
                echo "\n<span id=prop_".md5($aClass[$i]['id']).">\n";
                echo __get_all_properties_for_new_onto ($aClass[$i]['id'], $iMergingId);
                echo "\n</span>\n";
                echo '<div id="'.$sId.'" style="'.$div_style.'">';
                //_EchoNewOnto($iMergingId, $aClass[$i]['mdid'], $level + 1);
                echo '</div></div>';
        }
}
?>